package com.lagou;

import java.io.*;

/**
 * 响应信息封装类,提供核心方法输出静态资源
 */
public class Response {

    /**
     * 输出流
     */
    private OutputStream outputStream;

    public Response() {
    }

    public Response(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    public OutputStream getOutputStream() {
        return outputStream;
    }

    public void setOutputStream(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    /**
     * 输出指定字符串
     *
     * @param context
     */
    public void output(String context) throws IOException {
        outputStream.write(context.getBytes());
    }

    /**
     * 根据请求的url,找到对应的静态资源,并返回
     *
     * @param path
     */
    public void outputHtml(String path) throws IOException {
        //获取静态资源文件的绝对路径
        String absoluteResourcePath = StaticResourceUtil.getAbsolutePath(path);

        //输入静态资源文件
        File file = new File(absoluteResourcePath);
        if (file.exists() && file.isFile()) {
            StaticResourceUtil.outputStaticResource(new FileInputStream(file), outputStream);
        } else {
            //输出404
            output(HttpProtocolUtils.getHttpHeader404());
        }
    }
}
